<template>
	<view>
		<view class="cu-list menu" :class="[menuBorder ? 'sm-border' : '', menuCard ? 'card-menu margin-top' : '']">
			<view class="cu-item" :class="menuArrow ? 'arrow' : ''">
				<view class="content">文件上传</view>
				<view class="action">
					<button class="cu-btn round bg-green shadow" @tap="ChooseFile(index)">
						<text class="cuIcon-upload"></text>
						上传
					</button>
				</view>
			</view>
			<view v-for="(item, ind) in fileList" :key="ind" class="cu-item" :class="menuArrow ? 'arrow' : ''">
				<view class="content" style="overflow: hidden;text-overflow: ellipsis;">
					<text class="text-grey">
						<text class="cuIcon-tagfill text-red  margin-right-xs"></text>
						{{ item.fileName }}
					</text>
				</view>
				<view class="action">
					<view class="cu-tag round bg-blue light" @tap="ViewFile" :data-url="item.fileUrl">预览</view>
					<view class="cu-tag round bg-olive light" @tap="downLoad" :data-url="item.fileUrl">下载</view>
					<view class="cu-tag round bg-red light" @tap.stop="DelImg(index, ind)" :data-index="ind">删除</view>
				</view>
			</view>
		</view>
		<l-file ref="lFile" @up-success="upSuccess"></l-file>
		<view ref="input" class="input" hidden="true"></view>
	</view>
</template>

<script>
var sMD5 = require('common/js/md5.js');
import { mapState,mapActions} from 'vuex';
export default {
	data() {
		return {
			// 文件列表
			fileList: [],
			res: {},
			// 需要删除的文件列表
			needDel: []
		};
	},
	props: {
		// 类型
		bizKey: {
			type: String,
			default: ''
		},
		// 最大可上传量
		max: {
			type: Number,
			default: 4
		}
	},
	watch: {
		// 当上传或者删除之后通知父组件
		fileList() {
			let result = {};
			result.normal = this.fileList.map(item => {
				return item.id;
			});
			result.del = this.needDel;
			this.$emit('addOrDel', result);
		}
	},
	computed: {
		...mapState(['HOST_URL', 'sessionId'])
	},
	mounted() {
		
		// H5端图片上传
		// #ifdef H5
		var that = this;
		var input = document.createElement('input');
		input.type = 'file';
		input.id = 'fileAll';
		input.style.display = 'none';
		input.onchange = event => {
			that.uploadImgH5();
		};
		this.$refs.input.$el.appendChild(input);
		// #endif
	},
	methods: {
		...mapActions(["authInfo"]),
		// 文件预览
		ViewFile(e) {
			let filePath = e.currentTarget.dataset.url;
			console.log(filePath);
			// #ifdef APP-PLUS || MP-WEIXIN
			filePath = 'http://demo.jeesite.com/js/userfiles/fileupload/201907/1148170743879204866.doc';
			/* 预览临时文件 */
			this.$refs.lFile.download(filePath).then(path => {
				this.$refs.lFile.open(path);
			});
			// #endif
			// #ifdef H5
			uni.navigateTo({
				url: '/components/js-file/view?url=http://demo.jeesite.com/js/userfiles/fileupload/201907/1148170743879204866.doc',
				animationType: 'zoom-out'
			});
			// #endif
		},
		upSuccess(val) {
			let result = JSON.parse(val.data.id);
			let that = this;
			if (result.result == 'true') {
				result.fileUpload.fileUrl = that.HOST_URL + result.fileUpload.fileUrl;
				var obj = {};
				obj.id = result.fileUpload.id;
				obj.fileUrl = result.fileUpload.fileUrl;
				obj.fileName = result.fileUpload.fileName;
				that.fileList.push(obj);
			}
		},
		// 下载文件
		downLoad(e) {
			let filePath = e.currentTarget.dataset.url;
			// #ifdef H5
			uni.showModal({
				title: '',
				content: '确定要下载么？下载文件会关闭该程序',
				cancelText: '取消',
				confirmText: '确定',
				success: res => {
					if (res.confirm) {
						window.open(filePath);
					}
				}
			});
			// #endif
		},
		// 微信文件上传
		uploadFileWeixin(para, name) {
			let md5Code = null;
			let that = this;
			// 检测文件md5
			wx.getFileSystemManager().readFile({
				filePath: para.path, //选择图片返回的相对路径
				// encoding: 'binary', //编码格式
				success: res => {
					//成功的回调
					console.log('data:image/png;base64,', res);
					console.log(res.data);
					var spark = new sMD5.ArrayBuffer();
					spark.append(res.data);
					md5Code = spark.end(false);
					// 开始上传
					wx.uploadFile({
						url: that.HOST_URL + '/a/file/upload?__ajax=json&' + '__sid=' + that.sessionId,
						filePath: para.path,
						name: 'file',
						formData: {
							fileMd5: md5Code,
							fileName: name
						},
						success(res) {
							res.data = JSON.parse(res.data);
							if (res.statusCode == 200 && res.data) {
								if (res.data.result == 'true') {
									that.fileList.push(res.data.fileUpload);
									console.log(that.fileList);
								}
								if (res.data.result == 'login') {
									that.autoLogin().then(function(){
										that.uploadFileWeixin(res, name);
									})
								}
							} 
						},
						fail(res) {
							uni.showToast({
								title: "有文件上传失败",
								icon: "none"
							})
						}
					});
				}
			});
		},
		// 选择文件
		ChooseFile(ind) {
			// #ifdef H5
			document.getElementById('fileAll').click();
			// #endif
			// #ifdef MP-WEIXIN
			var that = this;
			wx.chooseMessageFile({
				count: this.max - this.fileList.length,
				type: 'file',
				success(res) {
					let tempFilePaths = res.tempFiles;
					for (let k = 0; k < tempFilePaths.length; k++) {
						let name = res.tempFiles[k].name;
						that.uploadFileWeixin(res.tempFiles[k], name)
					}
				}
			});
			// #endif
			// #ifdef APP-PLUS
			var pages = getCurrentPages();
			var page = pages[pages.length - 1];
			var currentWebview = page.$getAppWebview();
			this.$refs.lFile.upload({
				currentWebview: currentWebview,
				url: this.HOST_URL + '/a/file/upload?__ajax=json&__sid=' + this.sessionId, //测试地址，记得更换
				name: 'file',
				formData: {
					fileMd5: this.sessionId + new Date().getTime(),
					bizKey: '',
					bizType: this.bizType,
					uploadType: 'application/vnd.ms-excel',
					__ajax: 'json',
					// fileName: this.sessionId + new Date().getTime() + '.doc',
					// fileUploadId: 1169932019772755969,
					// fileEntityId: 1169932019772755970,
					id: 'WU_FILE_0',
					name: '1243231.doc',
					// type: 'image/',
					size: 1024
				}
			});
			// #endif
		},
		// H5文件上传
		uploadImgH5() {
			// #ifdef H5
			var fData = new FormData();
			var index1 = document.getElementById('fileAll').value.lastIndexOf('.');
			var index2 = document.getElementById('fileAll').value.length;
			var suffix = document.getElementById('fileAll').value.substring(index1, index2); //后缀名
			fData.append('file', document.getElementById('fileAll').files[0]);
			fData.append('fileMd5', new Date().getTime() + this.sessionId);
			fData.append('bizKey', '');
			fData.append('bizType', this.bizType);
			fData.append('uploadType', 'application/vnd.ms-excel');
			fData.append('fileName', document.getElementById('fileAll').files[0].name);
			fData.append('id', 'WU_FILE_0');
			fData.append('name', new Date().getTime());
			//fData.append('type', 'image/' + suffix.replace('.', ''));
			fData.append('size', document.getElementById('fileAll').size);
			var xhr = new XMLHttpRequest();
			xhr.open('POST', this.HOST_URL + '/a/file/upload?__ajax=json&__sid=' + this.sessionId, true);
			let that = this;
			xhr.onreadystatechange = function() {
				console.log(xhr.readyState);
				if (xhr.readyState == 4) {
					var result = JSON.parse(xhr.responseText);
					if (result.result == 'true') {
						result.fileUpload.fileUrl = that.HOST_URL + result.fileUpload.fileUrl;
						var obj = {};
						obj.id = result.fileUpload.id;
						obj.fileUrl = result.fileUpload.fileUrl;
						obj.fileName = result.fileUpload.fileName;
						that.fileList.push(obj);
						document.getElementById('fileAll').value = '';
					}
				}
			};
			//上传成功
			xhr.send(fData);
			// #endif
		},
		// 图片删除
		DelImg(index, ind) {
			uni.showModal({
				title: '',
				content: '确定要删除吗？',
				cancelText: '取消',
				confirmText: '确定',
				success: res => {
					if (res.confirm) {
						let obj = this.fileList.splice(ind, 1);
						this.needDel.push(obj[0].id);
					}
				}
			});
		}
	}
};
</script>
<style></style>
